package role

import (
	"context"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/text/gstr"
	"github.com/gogf/gf/v2/util/gconv"
	"ruoyi-vue-pro-go/api/common"
	v1 "ruoyi-vue-pro-go/api/role/v1"
	userrolev1 "ruoyi-vue-pro-go/api/userrole/v1"
	"ruoyi-vue-pro-go/internal/consts"
	"ruoyi-vue-pro-go/internal/dao"
	"ruoyi-vue-pro-go/internal/model/do"
	"ruoyi-vue-pro-go/internal/model/entity"
	"ruoyi-vue-pro-go/internal/service"
	"ruoyi-vue-pro-go/utility/excel"
)

type (
	sRole struct{}
)

func init() {
	service.RegisterRole(New())
}

func New() service.IRole {
	return &sRole{}
}

func (s *sRole) GetOne(ctx context.Context, req *v1.GetOneReq) (res *v1.GetOneRes, err error) {
	res = &v1.GetOneRes{}
	err = dao.SystemRole.Ctx(ctx).Where(do.SystemRole{
		Id: req.Id,
	}).Scan(&res.SystemRole)
	return
}

func (s *sRole) GetList(ctx context.Context, req *v1.GetListReq) (res *v1.GetListRes, err error) {
	res = &v1.GetListRes{}
	err = dao.SystemRole.Ctx(ctx).Scan(&res.List)
	return
}

func (s *sRole) GetListByUserId(ctx context.Context, req *v1.GetListByUserIdReq) (res *v1.GetListByUserIdRes, err error) {
	userroles, err := service.UserRole().GetListByUserId(ctx, &userrolev1.GetListByUserIdReq{
		UserId: req.UserId,
	})
	var ids []interface{}
	for _, userrole := range userroles.List {
		ids = append(ids, userrole.RoleId)
	}
	res = &v1.GetListByUserIdRes{}
	err = dao.SystemRole.Ctx(ctx).WhereIn("id", ids).Where(do.SystemRole{
		Status: 0,
	}).Scan(&res.List)
	if err != nil {
		return nil, err
	}
	return res, nil
}

func (s *sRole) GetPage(ctx context.Context, req *v1.GetPageReq) (res *v1.GetPageRes, err error) {
	res = &v1.GetPageRes{
		List:          make([]*entity.SystemRole, 0),
		CommonPageRes: &common.CommonPageRes{},
	}
	model := dao.SystemRole.Ctx(ctx)
	if req.Name != "" {
		model = model.WhereLike("name", "%"+req.Name+"%")
	}
	if req.Code != "" {
		model = model.WhereLike("code", "%"+req.Code+"%")
	}
	if req.Status != -1 {
		model = model.Where("status = ?", req.Status)
	}
	// 添加时间范围条件
	if len(req.CreateTime) != 0 {
		beginTime := gtime.New(req.CreateTime[0])
		endTime := gtime.New(req.CreateTime[1])
		if beginTime != nil && endTime != nil {
			// 验证时间顺序
			if beginTime.Time.After(endTime.Time) {
				return nil, gerror.New("开始时间不能晚于结束时间")
			}

			model = model.WhereBetween("create_time", beginTime, endTime)
		} else if beginTime != nil {
			model = model.WhereGTE("create_time", beginTime)
		} else if endTime != nil {
			model = model.WhereLTE("create_time", endTime)
		}
	}
	r := ghttp.RequestFromCtx(ctx)
	tenantId := gconv.Int64(r.Header.Get("Tenant-Id"))
	model = model.Where(do.SystemRole{
		TenantId: tenantId,
	})
	if req.PageSize != 0 {
		res.PageNo = req.PageNo
		res.PageSize = req.PageSize
		model = model.Page(req.PageNo, req.PageSize)
	}
	err = model.ScanAndCount(&res.List, &res.Total, false)
	return
}

func (s *sRole) ExportExcel(ctx context.Context, req *v1.ExportExcelReq) (res *v1.ExportExcelRes, err error) {
	res = &v1.ExportExcelRes{}
	// 1. 获取角色数据
	roleList, err := service.Role().GetList(ctx, &v1.GetListReq{})
	if err != nil {
		return nil, gerror.Wrap(err, "获取角色数据失败")
	}

	// 2. 创建导出器
	exporter := excel.NewGenericExporter(
		"角色列表.xlsx",
		roleList.List,
		excel.WithFields(consts.RoleExportFieldsOrder...),
		excel.WithHeaderMap(consts.RoleExportFields),
	)

	// 3. 执行导出
	r := ghttp.RequestFromCtx(ctx)
	if err := exporter.Export(ctx, r.Response); err != nil {
		return nil, gerror.Wrap(err, "导出角色列表失败")
	}

	// 4. 终止后续处理
	r.ExitAll()
	return nil, nil
}

func (s *sRole) AssignRoleDataScope(ctx context.Context, req *v1.AssignRoleDataScopeReq) (res *v1.AssignRoleDataScopeRes, err error) {
	res = &v1.AssignRoleDataScopeRes{}
	_, err = dao.SystemRole.Ctx(ctx).WhereIn("id", req.RoleId).Update(do.SystemRole{
		DataScope: req.DataScope,
	})
	if err != nil {
		return nil, err
	}
	return res, nil
}

func (s *sRole) Create(ctx context.Context, req *v1.CreateReq) (res *v1.CreateRes, err error) {
	res = &v1.CreateRes{}
	// 这里需要获取当前用户名和租户id
	r := ghttp.RequestFromCtx(ctx)
	username := r.GetCtxVar("username").String()
	tenantId := gconv.Int64(r.Header.Get("Tenant-Id"))
	req.TenantId = tenantId
	req.Creator = username
	req.Updater = username
	var cls = dao.SystemRole.Columns()
	count, err := dao.SystemRole.Ctx(ctx).
		Where(cls.Name, req.Name).Where(cls.Code, req.Code).Count()
	if err != nil {
		return res, err
	}
	if count > 0 {
		return res, gerror.NewCode(gcode.CodeDbOperationError, "角色已存在")
	}
	_, err = dao.SystemRole.Ctx(ctx).Data(req).Insert()
	if err != nil {
		return res, gerror.NewCode(gcode.CodeDbOperationError, "role create failed")
	}
	return
}

func (s *sRole) Delete(ctx context.Context, req *v1.DeleteReq) (res *v1.DeleteRes, err error) {
	res = &v1.DeleteRes{}
	var cls = dao.SystemRole.Columns()
	_, err = dao.SystemRole.Ctx(ctx).Where(cls.Id, req.Id).Delete()
	if err != nil {
		return nil, gerror.NewCode(gcode.CodeDbOperationError, "role delete failed")
	}
	return
}

func (s *sRole) DeleteList(ctx context.Context, req *v1.DeleteListReq) (res *v1.DeleteListRes, err error) {
	res = &v1.DeleteListRes{}
	var cls = dao.SystemRole.Columns()
	// 参数转换
	ids := gconv.Ints(gstr.Split(req.Ids, ","))
	if len(ids) == 0 {
		return nil, gerror.New("无效的ID参数")
	}
	_, err = dao.SystemRole.Ctx(ctx).WhereIn(cls.Id, ids).Delete()
	if err != nil {
		return nil, gerror.NewCode(gcode.CodeDbOperationError, "role delete list failed")
	}
	return
}
